﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Linq;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Estimate
{
    public partial class formProductIncomeDetail : FormMDIChildTemplate
    {
        readonly InvoiceIncome invoiceIncome;
        InvoiceRelocation invoiceRelocation;

        public formProductIncomeDetail(InvoiceIncome invoiceIncome)
        {
            InitializeComponent();
            this.invoiceIncome = invoiceIncome;
        }



        private void formMaterialProductIncomeDetail_Load(object sender, EventArgs e)
        {
            Text = String.Format("Накладна №{0} від {1} [{2}]",
                invoiceIncome.InvoiceIncomeNumber, invoiceIncome.DateCreate.ToShortDateString(), invoiceIncome.Firm.FirmName);

            invoiceRelocation = GetInvoiceRelocation();
            TranslateGrid();
            FillComboBox();
            FillProduct();
            FillInvoice();
        }

        private void FillComboBox()
        {
            comboBoxProductCategory.DataSource = context.ProductCategories.OrderBy(x => x.ProductCategoryName);
            comboBoxProductCategory.DisplayMember = "ProductCategoryName";
            comboBoxUnit.DataSource = context.Units.OrderBy(x => x.UnitName);
            comboBoxUnit.DisplayMember = "UnitName";
        }

        private void TranslateGrid()
        {
            root.TranslateGrid(gridProduct);
            root.TranslateGrid(gridInvoice);
        }

        private InvoiceRelocation GetInvoiceRelocation()
        {
            var invoice = context.InvoiceRelocations.Where(x => x.InvoiceIncome == invoiceIncome);
            if (invoice.Count() == 0)
            {
                var invoiceRelocationNew = new InvoiceRelocation();
                invoiceRelocationNew.DateCreate = invoiceIncome.DateCreate;
                invoiceRelocationNew.InvoiceIncome = invoiceIncome;
                invoiceRelocationNew.InvoiceRelocationNumber = 1;
                if (context.InvoiceRelocations.Count() > 0)
                    invoiceRelocationNew.InvoiceRelocationNumber =
                        context.InvoiceRelocations.Max(x => x.InvoiceRelocationNumber) + 1;
                invoiceRelocationNew.Remark = "Прихідна накладна № " + invoiceIncome.InvoiceIncomeNumber;
                invoiceRelocationNew.StoreHouseToID = invoiceIncome.StoreHouseID;
                context.InvoiceRelocations.InsertOnSubmit(invoiceRelocationNew);
                root.Submit(false);
                return invoiceRelocationNew;
            }
            return invoice.First();
        }

        public void FillInvoice()
        {
            var invoice = from invoiceIncomeToHistories in context.InvoiceIncomeToHistories
                          from histories in context.ProductHistories
                          where
                              invoiceIncomeToHistories.ProductHistory == histories &&
                              invoiceIncomeToHistories.InvoiceIncome == invoiceIncome
                          select new ProductInInvoice()
                                     {
                                         Count = invoiceIncomeToHistories.Count,
                                         InvoiceToHistoryID = invoiceIncomeToHistories.InvoiceIncomeToHistoryID,
                                         Price = invoiceIncomeToHistories.Price,
                                         PriceTotal = invoiceIncomeToHistories.PriceTotal,
                                         ProductName = histories.Product.ProductName,
                                         UnitName = histories.Product.Unit.UnitName
                                     };
            productInInvoiceBindingSource.DataSource = invoice;
        }



        private void FillProduct()
        {
            if (checkBoxNewProduct.Checked) productBindingSource.DataSource = null;
            else
            {
                IQueryable<Product> products = context.Products;
                if (textBoxFindProductName.Text.Length > 0)
                    products = products.Where(x => x.ProductName.Contains(textBoxFindProductName.Text));
                if (textBoxFindProductCode.Text.Length > 0)
                    products = products.Where(x => x.ProductCode.Contains(textBoxFindProductCode.Text));
                productBindingSource.DataSource = products.ToArray();
            }
        }

        private void textBoxProductCode_TextChanged(object sender, EventArgs e)
        { FillProduct(); }

        private void textBoxProductName_TextChanged(object sender, EventArgs e)
        { FillProduct(); }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            if (totalPrice == 0) return;

            Product product;
            if(checkBoxNewProduct.Checked)
            {
                product = new Product();
                product.ProductCategory = (ProductCategory) comboBoxProductCategory.SelectedItem;
                product.Unit = (Unit) comboBoxUnit.SelectedItem;
                product.ProductCode = textBoxNewProductCode.Text;
                product.ProductName = textBoxNewProductName.Text;
                context.Products.InsertOnSubmit(product);
                root.Submit();
            }
            else product = (Product)productBindingSource.Current;
            if(product==null ) return;

            var history = new ProductHistory();
            history.Cnt = count;
            history.DateSet = invoiceIncome.DateCreate;
            history.StatusID = 10;
            history.StoreHouse = null;
              
            product.ProductHistories.Add(history);

            root.Submit(false);

            var invoiceIncomeToHistory = new InvoiceIncomeToHistory();
            invoiceIncomeToHistory.Count = count;
            invoiceIncomeToHistory.ProductHistory = history;
            invoiceIncomeToHistory.InvoiceIncome = invoiceIncome;
            invoiceIncomeToHistory.Price = price;
            invoiceIncomeToHistory.PriceTotal = totalPrice;
            root.Submit(false);

            var invoiceIncomePrice = new InvoiceIncomePrice();
            invoiceIncomePrice.Count = count;
            invoiceIncomePrice.DateSet = invoiceIncome.DateCreate;
            invoiceIncomePrice.InvoiceIncomeToHistory = invoiceIncomeToHistory;
            invoiceIncomePrice.Price = priceDollar;
            context.InvoiceIncomePrices.InsertOnSubmit(invoiceIncomePrice );
            root.Submit();

            var historyRelocation = new ProductHistory();
            historyRelocation.Cnt = count;
            historyRelocation.DateSet = invoiceIncome.DateCreate;
            historyRelocation.Product = product;
            historyRelocation.StatusID = 20;
            historyRelocation.StoreHouse = invoiceIncome.StoreHouse;
            root.Submit(false);

            var invoiceRelocationToHistory = new InvoiceRelocationToHistory();
            invoiceRelocationToHistory.InvoiceRelocation = invoiceRelocation;
            invoiceRelocationToHistory.ProductHistory = historyRelocation;
            invoiceRelocationToHistory.Count = count;
            invoiceRelocationToHistory.Price = price;
            invoiceRelocationToHistory.PriceTotal = totalPrice;
            invoiceRelocationToHistory.InvoiceIncomeToHistory = invoiceIncomeToHistory  ;
            root.Submit();

            checkBoxNewProduct.Checked = false;
            FillProduct();
            FillInvoice();
        }

        private void textBoxCount_TextChanged(object sender, EventArgs e)
        { CalcTotalPrice(); }

        private void textBoxPrice_TextChanged(object sender, EventArgs e)
        { CalcTotalPrice(); }

        decimal count;
        decimal price;
        decimal priceDollar;
        decimal totalPrice;

        private void CalcTotalPrice()
        {
            try
            {
                count = decimal.Parse(textBoxCount.Text);
                priceDollar  = decimal.Parse(textBoxPrice.Text);
                price = priceDollar*db.Dollar;
                totalPrice = decimal.Round(count * price, 3);
                textBoxPriceTotal.Text = totalPrice.ToString();
            }
            catch { totalPrice = 0; textBoxPriceTotal.Text = ""; }
        }

        private void buttonRemove_Click(object sender, EventArgs e)
        {
            var productInInvoice = (ProductInInvoice)productInInvoiceBindingSource.Current;
            if (productInInvoice != null)
                db.DeleteInvoiceIncomeToHistory
                    (db.GetInvoiceIncomeToHistory(productInInvoice.InvoiceToHistoryID));
            FillInvoice();
        }

        private void checkBoxNewProduct_CheckedChanged(object sender, EventArgs e)
        {
            panelProduct.Enabled = !checkBoxNewProduct.Checked;
            panelNewProduct.Enabled = checkBoxNewProduct.Checked;
            FillProduct();
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {

            var reportInvoiceIncome = new reportInvoiceIncome();
            reportInvoiceIncome.DataSource = productInInvoiceBindingSource;

            //reportInvoiceIncome.DataSource = invoice;

            reportInvoiceIncome.xrLabelFirmTo.Lines = db.GetFirmOwn().GetFullDescription();

            reportInvoiceIncome.xrLabelFirmFrom.Lines = invoiceIncome.Firm.GetFullDescription();
            reportInvoiceIncome.xrLabelPayer.Text = invoiceIncome.Payer;
            reportInvoiceIncome.xrLabelStoreHouse.Text = invoiceIncome.StoreHouse.StoreHouseName;
            reportInvoiceIncome.xrLabelRemark.Text = invoiceIncome.Remark;
            reportInvoiceIncome.xrLabelHead1.Text = "Прихідна Накладна № " + invoiceIncome.InvoiceIncomeNumber;
            reportInvoiceIncome.xrLabelHead2.Text = "від " + invoiceIncome.DateCreate.ToShortDateString();

            decimal sum = 0;
            foreach (var invoiceIncomeToHistory in invoiceIncome.InvoiceIncomeToHistories)
                sum += invoiceIncomeToHistory.PriceTotal;
            decimal vAT = decimal.Round(sum/100*invoiceIncome.Vat, 3);
            decimal totalSum = vAT + sum;

            reportInvoiceIncome.xrLabelSum.Text = sum.ToString();
            reportInvoiceIncome.xrLabelSumTotal.Text = totalSum.ToString();
            reportInvoiceIncome.xrLabelVAT.Text = vAT.ToString();

            //reportInvoiceIncome.xrLabelTotalSumDescr.Text = totalSum.ToString();
            reportInvoiceIncome.xrLabelVAT2.Text = context.sfMoneyToWords(vAT);
            reportInvoiceIncome.ShowPreview();
        }
    }
}
